package com.zmn.brs.business.impl.event;

import com.github.ltsopensource.core.domain.Job;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.zmn.brs.business.interfaces.event.EventBService;
import com.zmn.brs.common.constant.TaskConst;
import com.zmn.brs.common.enums.EventTypeEnum;
import com.zmn.brs.cron.TaskScheduleModel;
import com.zmn.brs.model.entity.event.Event;
import com.zmn.brs.model.entity.event.EventQuery;
import com.zmn.brs.services.interfaces.event.EventService;
import com.zmn.brs.utils.CronUtil;
import com.zmn.manager.lts.interfaces.task.TaskManager;
import com.zmn.plat.common.dictionary.StatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 描述： 事件接口实现
 * @author chongw
 * @since 2021-07-14 15:49
 */
@Slf4j
@Service
public class EventBServiceImpl implements EventBService {

    public static final String TAG = "事件业务服务实现";

    @Resource
    private EventService eventService;

    @Resource
    private TaskManager taskManager;

    /**
     * 初始化事件job
     * @param eventId
     */
    public void initEventJob(Integer eventId){
        //派单客单价计算任务
        List<Event> eventList = Optional.ofNullable(eventService.listByQuery(EventQuery.builder()
                .eventId(eventId)
                .eventType(EventTypeEnum.ENGINEER_SALES.getTypeId())
                .build())).orElse(new ArrayList<>());
        eventList.forEach(o -> {
            refreshJob(o);
        });
    }
    /**
     * 初始化事件job
     * @param eventType
     */
    public void initEventTypeJob(Integer eventType){
        //派单客单价计算任务
        List<Event> eventList = Optional.ofNullable(eventService.listByQuery(EventQuery.builder()
                .eventType(eventType)
                .build())).orElse(new ArrayList<>());
        eventList.forEach(o -> {
            refreshJob(o);
        });

    }

    /**
     * 刷新任务状态
     * @param event
     */
    protected void refreshJob(Event event){
        Integer status = eventService.getStatusByEventId(event.getEventId());
        //如果是禁用，删除JOB
        if(StatusEnum.DISABLE.getCode().equals(status)){
            taskManager.cancelTask2(TaskConst.TASK_ID_BRS_ENGINEER_SALES);
        }
        //启用，提交JOB
        else {
            //判断如果triggerTime是cron表达式则初始化收款未支付金额任务
            String triggerTime = Optional.ofNullable(event.getTriggerTime()).orElse(TaskConst.SALES_DEFAULT_TIME);
            if (isCron(triggerTime)) {
                Job unpaidPush = new Job();
                unpaidPush.setTaskId(TaskConst.TASK_ID_BRS_ENGINEER_UNPAID_PUSH);
                unpaidPush.setCronExpression(triggerTime);
                unpaidPush.setReplaceOnExist(true);
                unpaidPush.setParam(TaskManager.SHARD_FIELD, TaskConst.TASK_ID_BRS_ENGINEER_UNPAID_PUSH);
                taskManager.submitTask2(unpaidPush);
            }
            else {
                String[] time = triggerTime.split(":");
                Job salesJob = new Job();
                salesJob.setTaskId(TaskConst.TASK_ID_BRS_ENGINEER_SALES);
                salesJob.setCronExpression(CronUtil.createCronExpression(
                        TaskScheduleModel.builder()
                                .jobType(1)
                                .hour(Integer.parseInt(time[0]))
                                .minute(Integer.parseInt(time[1]))
                                .second(Integer.parseInt(time[2]))
                                .build()));
                salesJob.setReplaceOnExist(true);
                salesJob.setParam(TaskManager.SHARD_FIELD, TaskConst.TASK_ID_BRS_ENGINEER_SALES);
                taskManager.submitTask2(salesJob);
            }
        }
    }

    /**
     * 判断字符串是不是cron表达式
     * @return
     */
    private Boolean isCron(String triggerTime) {
        if (triggerTime.endsWith("?")) {
            return true;
        }
        return false;
    }
}
